package com.xilixili.miaomi.wechat.recyclerview;

/**
 * Created by Marshal Chen on 3/8/2016.
 */

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import com.xilixili.miaomi.wechat.R;
import com.xilixili.miaomi.wechat.cache.ImageDownloader;
import com.xilixili.miaomi.wechat.cache.OnImageDownload;
import com.xilixili.miaomi.wechat.entity.ContentInfo;
import com.xilixili.miaomi.wechat.entity.ImageInfo;
import com.xilixili.miaomi.wechat.entity.TweetInfo;
import com.xilixili.miaomi.wechat.entity.UserInfo;
import com.xilixili.miaomi.wechat.ninegridview.NineGridlayout;

import java.util.List;


public class SimpleAdapter extends UltimateViewAdapter {
    private String TAG = getClass().getSimpleName();

    private List<TweetInfo> tweetInfos;
    private ImageDownloader imageDownloader;
    private Activity activity;

    public SimpleAdapter(List<TweetInfo> tweetInfos, Activity activity) {
        this.tweetInfos = tweetInfos;
        this.activity = activity;
    }


    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (position < getItemCount() && (customHeaderView != null ? position < tweetInfos.size() : position < tweetInfos.size()) && (customHeaderView != null ? position > 0 : true)) {
            String content = tweetInfos.get(position).getContent();
            Log.d(TAG, "onBindViewHolder content " + content + ", position " + position);
            if(content == null || content.isEmpty()){
                ((ViewHolder) holder).contentTV.setVisibility(View.GONE);
            } else {
                ((ViewHolder) holder).contentTV.setVisibility(View.VISIBLE);
                ((ViewHolder) holder).contentTV.setText(content);
            }

            List<ImageInfo> imageInfos = tweetInfos.get(position).getImages();
            if(imageInfos == null || imageInfos.size() == 0) {
                ((ViewHolder) holder).nineGridlayout.setVisibility(View.GONE);
            } else {
                ((ViewHolder) holder).nineGridlayout.setVisibility(View.VISIBLE);
                ((ViewHolder) holder).nineGridlayout.setImageInfosData(imageInfos);
            }

            List<ContentInfo> commentInfos = tweetInfos.get(position).getComments();
            if(commentInfos == null || commentInfos.size() == 0) {
                ((ViewHolder) holder).commentTitleTV.setVisibility(View.GONE);
                ((ViewHolder) holder).commentLayout.setVisibility(View.GONE);
            } else {
                ((ViewHolder) holder).commentTitleTV.setVisibility(View.VISIBLE);
                ((ViewHolder) holder).commentLayout.setVisibility(View.VISIBLE);

                LinearLayout layout = new LinearLayout(((ViewHolder) holder).getContext());
                for(ContentInfo info : commentInfos) {
                    Log.d(TAG, "comment " + info.toString());
                    LayoutInflater inflater = LayoutInflater.from(((ViewHolder) holder).getContext());
                    inflater.inflate(R.layout.item_content, layout);
                    TextView user = (TextView)layout.findViewById(R.id.comment_name);
                    TextView comment = (TextView)layout.findViewById(R.id.comment);
                    if(info != null && info.getContent() != null && !info.getContent().isEmpty()
                            && info.getSender()!= null && info.getSender().getNick() != null
                            && !info.getSender().getNick().isEmpty()){
                        try{
                            Log.d(TAG, "comment nickname " +info.getSender().getNick().toString());
                            user.setText(info.getSender().getNick()+" : ");
                            comment.setText(info.getContent());
                            ((ViewHolder) holder).commentLayout.addView(layout);
                        }  catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }

    }

    @Override
    public int getAdapterItemCount() {
        return tweetInfos.size();
    }

    @Override
    public RecyclerView.ViewHolder newFooterHolder(View view) {
        // return new itemCommonBinder(view, false);
        return new UltimateRecyclerviewViewHolder<>(view);
    }

    @Override
    public RecyclerView.ViewHolder newHeaderHolder(View view) {
        return new UltimateRecyclerviewViewHolder<>(view);
    }

    @Override
    public UltimateRecyclerviewViewHolder onCreateViewHolder(ViewGroup parent) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_view_adapter, parent, false);
        ViewHolder vh = new ViewHolder(v);
        if(imageDownloader == null) {
            imageDownloader = new ImageDownloader();
        }
        return vh;
    }


    public void insert(TweetInfo info, int position) {
        insertInternal(tweetInfos, info, position);
    }

    public void remove(int position) {
        removeInternal(tweetInfos, position);
    }

    public void clear() {
        clearInternal(tweetInfos);
    }


    public void swapPositions(int from, int to) {
        swapPositions(tweetInfos, from, to);
    }


    @Override
    public long generateHeaderId(int position) {
        // URLogs.d("position--" + position + "   " + getItem(position));
        //if (getItem(position).length() > 0)
        //    return getItem(position).charAt(0);
        //else return -1;
        return position;
    }

    @Override
    public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.stick_header_item, viewGroup, false);
        if(imageDownloader == null) {
            imageDownloader = new ImageDownloader();
        }
        return new RecyclerView.ViewHolder(view) {
        };
    }

    @Override
    public void onBindHeaderViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
        if (position < getItemCount() && (customHeaderView != null ? position < tweetInfos.size() : position < tweetInfos.size()) && (viewHolder != null ? position > 0 : true)) {

            TextView textView = (TextView) viewHolder.itemView.findViewById(R.id.stick_text);
            //textView.setText(String.valueOf(getItem(position).charAt(0)));
            String name = "";
            if (tweetInfos != null && tweetInfos.size() > position
                    && tweetInfos.get(position) != null && tweetInfos.get(position).getSender() != null) {
                UserInfo info = tweetInfos.get(position).getSender();
                name = info.getNick() != null ? info.getNick() : info.getUsername();
            }
            textView.setText(name);
//        viewHolder.itemView.setBackgroundColor(Color.parseColor("#AA70DB93"));
            viewHolder.itemView.setBackgroundColor(Color.parseColor("#AAffffff"));

            ImageView imageView = (ImageView) viewHolder.itemView.findViewById(R.id.stick_img);
            String url = tweetInfos.get(position).getSender().getAvatar();
            imageView.setTag(url);
            android.util.Log.d(TAG, "imageView url: " + url + ", position: " + position);

            imageView.setImageResource(R.mipmap.ic_launcher);
            Log.d(TAG, "imageDownload url:" + url + ", iamgeView:" + imageView + ", activity:" + activity + "");
            imageDownloader.imageDownload(url, imageView,"/yanbin",activity, new OnImageDownload() {
                @Override
                public void onDownloadSucc(Bitmap bitmap,
                                           String c_url,ImageView mimageView) {
                    ImageView imageView = (ImageView) viewHolder.itemView.findViewWithTag(c_url);
                    if (imageView != null) {
                        imageView.setImageBitmap(bitmap);
                        imageView.setTag("");
                    }
                }
            });
        }
    }

    @Override
    public void onItemMove(int fromPosition, int toPosition) {
        if (fromPosition > 0 && toPosition > 0) {
            swapPositions(fromPosition, toPosition);
//        notifyItemMoved(fromPosition, toPosition);
            super.onItemMove(fromPosition, toPosition);
        }

    }

    @Override
    public void onItemDismiss(int position) {
        if (position > 0) {
            remove(position);
            // notifyItemRemoved(position);
//        notifyDataSetChanged();
            super.onItemDismiss(position);
        }

    }
//
//    private int getRandomColor() {
//        SecureRandom rgen = new SecureRandom();
//        return Color.HSVToColor(150, new float[]{
//                rgen.nextInt(359), 1, 1
//        });
//    }

    public void setOnDragStartListener(OnStartDragListener dragStartListener) {
        mDragStartListener = dragStartListener;

    }

    class ViewHolder extends UltimateRecyclerviewViewHolder {

        TextView contentTV;
        NineGridlayout nineGridlayout;
        TextView commentTitleTV;
        LinearLayout commentLayout;
        ProgressBar progressBarSample;
        View item_view;

        public ViewHolder(View itemView) {
            super(itemView);

            contentTV = (TextView) itemView.findViewById(
                    R.id.textview);
            nineGridlayout = (NineGridlayout) itemView.findViewById(R.id.iv_ngrid_layout);
            //progressBarSample = (ProgressBar) itemView.findViewById(R.id.progressbar);
            //progressBarSample.setVisibility(View.GONE);
            commentTitleTV = (TextView)itemView.findViewById(R.id.comment_title);
            commentLayout = (LinearLayout) itemView.findViewById(R.id.layout_comments);
            item_view = itemView.findViewById(R.id.itemview);
        }

        @Override
        public void onItemSelected() {
            itemView.setBackgroundColor(Color.LTGRAY);
        }

        @Override
        public void onItemClear() {
            itemView.setBackgroundColor(0);
        }
    }

    public TweetInfo getItem(int position) {
        if (customHeaderView != null)
            position--;
        // URLogs.d("position----"+position);
        if (position >= 0 && position < tweetInfos.size())
            return tweetInfos.get(position);
        else return null;
    }

}